import { defineStore } from 'pinia'
import type { UserData } from './type/user'
import { type IUser } from '@/request/types/userType'
import { getUserInfoAPI, loginAPI } from '@/request/modules/user'

export const useUserStore = defineStore('userStore', {
  // 定义 state
  state: () => ({
    userInfo: JSON.parse(
      localStorage.getItem('userInfo') || '{}'
    ) as Partial<UserData>,
  }),
  // 定义 actions（相当于组合式 API 中的方法）
  actions: {
    async login(data: IUser) {
      const result = await loginAPI(data)
      if (result.data.errno === 0) {
        this.userInfo = result.data.data
        localStorage.setItem('userInfo', JSON.stringify(result.data.data))
      }
    },
    setToken(token: string) {
      this.userInfo.token = token
    },
    async getUserInfo() {
      const result = await getUserInfoAPI()
      Object.assign(this.userInfo, result.data.data)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    logout() {
      localStorage.removeItem('userInfo')
      this.userInfo = {}
    },
  },
})

export default useUserStore
